<?php

namespace app\store\model;

use app\common\model\Video as VideoModel;

/**
 * 商品模型
 * Class Goods
 * @package app\store\model
 */
class Video extends VideoModel
{
    /**
     * 添加
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {
        if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传视频封面图';
            return false;
        }
        $data['content'] = isset($data['content']) ? $data['content'] : '';
        $data['wxapp_id'] = self::$wxapp_id;

        // 开启事务
        $this->startTrans();
        try {
            // 添加商品
            $this->allowField(true)->save($data);
            // 商品图片
            $this->addGoodsImages($data['images']);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 添加图片
     * @param $images
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function addGoodsImages($images)
    {
        $this->image()->delete();
        $data = array_map(function ($image_id) {
            return [
                'image_id' => $image_id,
                'wxapp_id' => self::$wxapp_id
            ];
        }, $images);
        return $this->image()->saveAll($data);
    }

    /**
     * 编辑
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传视频封面图';
            return false;
        }
        //var_dump($data);die();
        $data['content'] = isset($data['content']) ? $data['content'] : '';
        $data['wxapp_id'] = self::$wxapp_id;
        return $this->transaction(function () use ($data) {
            // 保存
            $this->allowField(true)->save($data);
            // 图片
            $this->addGoodsImages($data['images']);
            return true;
        });
    }

    /**
     * 修改状态
     * @param $state
     * @return false|int
     */
    public function setStatus($state)
    {
        return $this->allowField(true)->save(['room_status' => $state ? 10 : 20]) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->allowField(true)->save(['is_delete' => 1]);
    }

    /**
     * 获取当前商品总数
     * @param array $where
     * @return int|string
     * @throws \think\Exception
     */
    public function getRoomTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }

}
